use crate::cache::Cache;
use crate::parts::{Cate, Counter};
use anyhow::Result;
use crate::asf::AddLicenseResult;

mod asf;
mod cache;
mod parts;
mod consts;


#[tokio::main]
async fn main() -> Result<()> {
    println!("========================================");
    println!("     Steam free-to-keep 自动认领脚本     ");
    println!("========================================");

    let mut counter = Counter::default();
    println!("流程开始: {}", counter.get_start_time_str());

    // --- 初始化sled数据库缓存 ---
    println!("[缓存] 正在初始化sled数据库");
    let cache = cache::Cache::new(consts::DB_FILE)?;
    println!("[缓存] 已加载sled数据库 : 包含 {} 条记录。", cache.len());

    // --- 步骤 1: 获取并分割ID ---
    println!("[数据源] 正在从Gist获取ID列表...");
    let response_text = reqwest::get(consts::GIST_URL).await?.text().await?;

    let mut sub_ids = Vec::new();
    let mut app_ids = Vec::new();

    for line in response_text.lines() {
        let trimmed_line = line.trim();
        if let Some(subid) = trimmed_line.strip_prefix("s/") {
            sub_ids.push(subid.to_string());
        } else if let Some(appid) = trimmed_line.strip_prefix("a/") {
            app_ids.push(appid.to_string());
        }
    }
    println!(
        "[数据源] 获取成功！发现 {} 个SubID，{} 个AppID。",
        sub_ids.len(),
        app_ids.len()
    );

    // --- 步骤 2: 处理ID ---
    let client = reqwest::Client::new();

    loop_processor(Cate::APPID, &client, &cache, app_ids, &mut counter).await?;
    loop_processor(Cate::SUBID, &client, &cache, sub_ids, &mut counter).await?;


    // --- 总结 ---
    counter.init_end_time();
    println!(
        "流程结束: {} , 总耗时: {} 秒",
        counter.get_end_time_str(),
        counter.time_diff_seconds()
    );
    println!("\n========================================");
    println!("所有任务处理完成！");
    println!("  -> 成功: {} 个", counter.get_success());
    println!("  -> 失败: {} 个", counter.get_fail());
    println!("  -> 跳过: {} 个", counter.get_skipped());
    println!("========================================");

    Ok(())
}

async fn loop_processor(
    cate: Cate,
    client: &reqwest::Client,
    cache: &Cache,
    ids: Vec<String>,
    counter: &mut Counter,
) -> Result<()> {
    let tag = &cate.to_string();
    println!("\n--- 开始处理 {} 列表 ---", tag);
    for appid in ids {
        println!("\n正在尝试认领 {} : {}", tag, appid);
        if cache.check(cate, &appid)? {
            println!("已在之前处理，跳过");
            counter.increase_skipped();
            continue;
        }
        let res: Result<AddLicenseResult> = match cate {
            Cate::SUBID => {
                asf::add_license_by_sub(client, &appid).await
            },
            Cate::APPID => {
                asf::add_license_by_app(client, &appid).await
            }
        };
        match res {
            Ok(result) => {
                if result.success {
                    println!(" -> ✅ 成功: {}", result.message);
                    counter.increase_success();
                } else {
                    println!(" -> ❌ 失败: {}", result.message);
                    counter.increase_fail();
                }
            }
            Err(e) => {
                println!(" -> ❌ 错误: 请求失败 - {}", e);
                counter.increase_fail();
            }
        }
        // 为了礼貌，在每个请求之间稍作等待
        tokio::time::sleep(std::time::Duration::from_secs(3)).await;
    }
    Ok(())
}

